from django.shortcuts import render, redirect
from django.views import View
from django.middleware.csrf import get_token
from django.http import JsonResponse
from django.views.decorators.http import require_GET
from django_redis import get_redis_connection
from process.models import ChatSession
from OpenAI.settings import RuiJiang_Base_Url
import requests, json, datetime


# Create your views here.


class USER_VIEW(View):

    # 注册
    def post(self, request):
        return render(request, 'user.html')

    # 手机验证码
    def get(self, request):
        return render(request, 'user.html')


@require_GET
def getCsrfToken(request):
    return JsonResponse({"code": 200, "csrfmiddlewaretoken": get_token(request)})


def user_login(request):
    try:
        data = json.loads(request.body.decode())
        username = data.get("username")
        password = data.get("password")
    except:
        return JsonResponse({"code": 400, "msg": "参数错误"})

    if not all([username, password]):
        return JsonResponse({"code": 400, "msg": "账号/密码错误"})
    url = f"{RuiJiang_Base_Url}user/client/login"
    params = {
        "username": username,
        "password": password,
        "__device": "web"
    }
    # 发送post进行访问
    response = requests.post(url, data=params)
    response = response.json()
    resp = {
        "code": 400,
        "msg": response.get("errorMsg"),
        "data": {}
    }
    if response['ret'] == 2:
        token = response["data"]["token"]
        userID = response["data"]["info"]["userID"]
        email = response["data"]["info"]["email"]
        phone = response["data"]["info"]["phone"]
        realName = response["data"]["info"]["realName"]
        sex = response["data"]["info"]["sex"]
        uuid = response["data"]["info"]["uuid"]
        resp['code'] = 200
        resp['msg'] = "登录成功"
        resp['data'] = response['data']
        save_token(userID, token)

        user_profile, created = UserProfile.objects.update_or_create(
            userID=userID,
            defaults={
                'username': username,
                'email': email,
                'phone': phone,
                'realName': realName,
                'sex': sex,
                'uuid': uuid,
            }
        )
        BILLING_TYPE = int(user_profile.billing_type)
        MEMBERSHIP_TYPE = int(user_profile.membership_type)
        EXPIRED = user_profile.expired

        if ((MEMBERSHIP_TYPE == 2 or MEMBERSHIP_TYPE == 3) and BILLING_TYPE == 1 and EXPIRED < datetime.datetime.now()) \
                or (BILLING_TYPE == 2 and all([True if value == 0 else False for key, value in user_profile.count.items()])):
            user_profile.BILLING_TYPE = 1
            user_profile.membership_type = 1
            user_profile.save()
        ChatSessionToRedis(userID, getChatSessionList(userID))

    return JsonResponse(resp)


def save_token(userID, token):
    conn = get_redis_connection()
    conn.set(userID, token, ex=60 * 60 * 2)


def getChatSessionList(userID):
    return [
        {"chatID": chat_session.chatID, "title": chat_session.chathistory_set.first().title,
         "creat_time": chat_session.creat_time.strftime('%Y-%m-%d %H:%M:%S')}
        for chat_session in ChatSession.objects.filter(userID=userID, state=True).order_by('-creat_time').all()
    ]


def ChatSessionToRedis(userID, ChatSessionList):
    conn = get_redis_connection('chat_sessions')
    conn.set(userID, json.dumps(ChatSessionList), ex=60 * 60 * 2)


def userprofile(request):
    try:
        userID = request.headers.get("userID", None)
        user_profile = UserProfile.objects.get(userID=userID)
        return JsonResponse({
            "code": 200,
            "msg": "获取用户信息成功",
            "data": {
                "username": user_profile.username,
                "email": user_profile.email,
                "phone": user_profile.phone,
                "member": user_profile.get_membership_type_display(),
                "expired": user_profile.expired.strftime("%Y-%m-%d %H:%M:%S"),
                "count": {key: value for key, value in user_profile.count.items()}
            }}
        )
    except:
        return JsonResponse({"code": 400, "msg": "用户不存在"})


def bing_wallpaper(request):
    redis_conn = get_redis_connection('bing_wallpapers')
    random_key = redis_conn.randomkey()
    random_wallpaper_url = 'https://www.bing.com/th?id=OHR.BodieNC_ROW3179695505_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp'
    if random_key:
        random_wallpaper_url = redis_conn.get(random_key).decode()
    return redirect(random_wallpaper_url)


from apscheduler.schedulers.background import BackgroundScheduler
from user.task import reset_count_task, bing_wallpapers
from user.models import UserProfile

scheduler = BackgroundScheduler(timezone='Asia/Shanghai')
scheduler.add_job(reset_count_task, 'cron', hour=0, name='reset_count_task', id='reset')
scheduler.add_job(bing_wallpapers, 'cron', hour=0, name='bing_wallpapers', id='bing')
scheduler.start()
